package no.gnet.edvd.web.controller.feeds;

import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

import no.gnet.edvd.DataStore;
import no.gnet.edvd.web.controller.CommonController;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.cache.CacheBuilder;

@Controller
public class SoccerGameFeed extends CommonController {

	static Logger logger = Logger.getLogger(SoccerGameFeed.class);

	private static ConcurrentMap<Object, Object> data = CacheBuilder.newBuilder().concurrencyLevel(1000)
			.maximumSize(3600).softValues().expireAfterWrite(120, TimeUnit.SECONDS).build().asMap();

	@Autowired
	DataStore datastore;

	@RequestMapping(value = "/soccerfeed/{league}/{limit}", method = RequestMethod.GET)
	public @ResponseBody
	String soccerfeed(@PathVariable String league, @PathVariable String limit) throws MalformedURLException,
			IOException {
		String key = league + "_" + limit;
		String cached = (String) data.get(key);
		if (cached == null) {
			URLConnection urlconn = new URL("https://api.statsfc.com/crowdscores/fixtures.php"
					+ "?key=VsIkrxOyDBTSi1KkdIl7gdFb5dqjvOihsJ1PxVnN&" + "domain=statsfc.com&competition=" + league
					+ "&group=&team=&from=&to=&limit=" + limit).openConnection();

			StringWriter writer = new StringWriter();
			IOUtils.copy(urlconn.getInputStream(), writer, "UTF-8");
			String theString = writer.toString();
			data.put(key, theString);
			return theString;
		} else {
			return cached;
		}
	}
}
